package logic

import (
	"context"
	"fmt"
	"vaildate/models"
	"vaildate/pkg"

	"vaildate/user_srv/internal/svc"
	"vaildate/user_srv/user_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type VailDateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVailDateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VailDateLogic {
	return &VailDateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VailDateLogic) VailDate(in *user_srv.VailDateRequest) (*user_srv.VailDateResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("code_no = ?", in.CodeNo).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("当前身份信息已被占用")
	}
	user = models.User{}
	if models.DB.Where("id = ？", in.UserId).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号不可用")
	}
	if user.CodeNo != "" {
		return nil, fmt.Errorf("当前账号已实名")
	}
	date := pkg.VailDate(in.CodeNo, in.RealName)
	if date.ErrorCode != 0 {
		return nil, fmt.Errorf("身份信息不存在，请联系公安或管理员")
	}
	if !(date.Result.Isok) {
		return nil, fmt.Errorf("身份验证不通过")
	}
	user.RealName = date.Result.Realname
	user.CodeNo = date.Result.Idcard
	if models.DB.Updates(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &user_srv.VailDateResponse{}, nil
}
